package com.easylinkin.linkappapi.knowledgebase.util;

import cn.hutool.core.collection.CollectionUtil;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoyang
 * @version 1.0
 * @date 2021/12/13
 * @description
 */
public class NodeUtil {

  /**
   * 根据父节点id 获取节点的所有子节点
   * @param id
   * @param list
   * @return
   */
  public static List<Node> getAllChildrenByRootId(Long id, List<Node> list){
    List<Node> result = new ArrayList<>();
    for (Node adModule : list) { // 根节点
      if (id.toString().equals(adModule.getPId())) {//0表示根节点,具体情况视事务情况定
        result.add(getChildren(adModule, list));
      }
    }
    return result;

  }

  /**
   * 递归获取子节点
   * @param module
   * @param list
   * @return
   */
  private static Node getChildren(Node module, List<Node> list) {
    List<Node> childNodes = new ArrayList<>();
    for (Node node : list) {
      if (node.getPId().equals(module.getId().toString())) {
        childNodes.add(getChildren(node, list));
      }
    }
    if (childNodes!=null && !childNodes.isEmpty()) {
      module.setChildren(childNodes);
    }
    return module;
  }

  /**
   * 检查请求节点是否是当前子节点
   * @param id 请求节点
   * @param treeDataList 当前节点的子节点列表
   * @return
   */
  public static Boolean checkChildNode(Long id,List<Node> treeDataList) {
    boolean flg = false;
    for (Node treeData : treeDataList) {
      if (treeData.getId().equals(id)) {
        flg = true;
        return flg;
      }
    }
    if(!flg){
      for (Node treeData : treeDataList) {
        if(CollectionUtil.isEmpty(treeData.getChildren())){
          continue;
        }
        flg = checkChildNode(id,treeData.getChildren());
        if(flg){
          return flg;
        }
      }
    }
    return flg;
  }

}
